import numpy as np
import pandas as pd
import umap
import joblib


def getNewLocations(nation, columnName, newValue):
    data = pd.read_excel("../completion/datas/completed2.xlsx")  # type: pd.DataFrame
    model = joblib.load('../model2.m')  # type: UMAP
    standardModel = joblib.load('../standardModel.m')
    # 寻找需要更新的数据的位置 rowIndex, columnIndex
    columnIndex = 0
    for i in range(len(data.columns)):
        if data.columns[i] == columnName:
            columnIndex = i
            break
    rowIndex = 0
    for i in range(len(data)):
        if data['indicator'][i] == nation:
            rowIndex = i
    oldValue = data.values[rowIndex][columnIndex]
    # 去掉模型中不需要的数据
    v = data.drop('indicator', 1).values

    # 插值
    if oldValue < newValue:
        interValues = np.linspace(oldValue, newValue, 10)
        print(interValues)
        interValues = interValues[1:]
        print(interValues)

    else:
        interValues = np.linspace(newValue, oldValue, 10)
        print(interValues)
        interValues = interValues[:-1]
        print(interValues)

    locations = []
    values = []
    # 对每个插值 进行降维
    for iv in interValues:
        v[rowIndex][columnIndex - 1] = iv
        scaled_v = standardModel.transform(v)
        embedding = model.transform([scaled_v[rowIndex]])
        locations.append(list(embedding[0]))
        values.append(iv)
    print(locations)
    # print(type(locations))
    locations = np.array(locations).tolist()
    values = np.array(values).tolist()
    # print(type(locations))
    return locations,values


if __name__ == '__main__':
    nation = "South Africa"
    columnName = "population"
    newValue = 1070000
    getNewLocations(nation, columnName, newValue)
# # 初始化变量
# nation = "South Africa"
# columnName = "population"
# newValue = 107000000
# # 读取数据 加载模型
# data = pd.read_excel("../completion/datas/completed2.xlsx")  # type: pd.DataFrame
# model = joblib.load('../model2.m')  # type: UMAP
# standardModel = joblib.load('../standardModel.m')
# # 寻找需要更新的数据的位置 rowIndex, columnIndex
# columnIndex = 0
# for i in range(len(data.columns)):
#     if data.columns[i] == columnName:
#         columnIndex = i
#         break
# rowIndex = 0
# for i in range(len(data)):
#     if data['indicator'][i] == nation:
#         rowIndex = i
# oldValue = data.values[rowIndex][columnIndex]
# # 去掉模型中不需要的数据
# v = data.drop('indicator', 1).values
#
# # 插值
# interValues = np.linspace(oldValue, newValue, 10)
# print(interValues)
# locations = []
# # 对每个插值 进行降维
# for iv in interValues:
#     v[rowIndex][columnIndex - 1] = iv
#     scaled_v = standardModel.transform(v)
#     embedding = model.transform([scaled_v[rowIndex]])
#     locations.append(embedding[0])
# print(locations)
# # oldRow = data[data['indicator'] == nation].values[0]
# # print(oldRow)
# # print(oldRow.shape)
# # oldRow[columnIndex] = newValue
# # model.transform
# # oldValue = data[column][data['indicator'] == nation].values[0]
